package com.yao.handler;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/10/9 23:00
 * FileName: LoginAuthenticationFailureHandler
 * Description:
 */

import com.alibaba.fastjson.JSONObject;
import com.yao.bean.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("登陆失败：{}",exception);
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        R r = new R();
        r.setCode(200);
        r.setMsg("认证失败，用户名密码错误");
        if(exception instanceof UsernameNotFoundException){
            r.setData("用户名："+exception.getMessage());
            out.write(JSONObject.toJSONString(r));
            out.flush();
            out.close();
            return;
        }
        r.setData(exception.getMessage());
        out.write(JSONObject.toJSONString(r));
        out.flush();
        out.close();
    }
}
